public class SearchPlanDocumentsVF{
  
    String planGroupNames = '';
    String status = '';
    String users = '';
    String roles = '';
    String templates = '';
    List<Sales_Contract__c> contracts = null;   
    String userProfileName = '';
    UserRole[] currentUserSubDetails = null;
    String currentUserTitle = '';
    Profile[] p = null;
    Boolean dispColumns = false;
    private String effectiveStartDate = '';
    private String effectiveEndDate = '';
    private Sales_Contract__c tempSC = new Sales_Contract__c(Effective_Start_Date__c = Date.today(), Effective_End_Date__c = Date.today());
    private Date effStartDate = null;
    private Date effEndDate = null;
    private Sales_Contract__c[] salesContractObj = null;
    String[] userOptionList = new List<String>();
    String[] rolesOptionList = new List<String>();
    String[] planGroupOptionList = new List<String>();
    String[] templateOptionList = new List<String>();
    List<User> uList = new List<User>();
    Plan_Document_Inquiry__c pdi = new Plan_Document_Inquiry__c();
    static String testVar = '';
    
    public SearchPlanDocumentsVF(String userId, String roleId)
    {
        currentUserSubDetails = [Select id, name, parentroleid, (select id, name, title from Users where IsActive = true order by name) from UserRole ur Where ur.ParentRoleId = :roleId order by name];
        for(Integer i=0; i<currentUserSubDetails.size(); i++)
        {
            getRolesAtDeeperLevel(currentUserSubDetails[i]);
        }

        for(UserRole role: currentUserSubDetails)
        {
            for(User u : role.Users)
                uList.add(u);
        }
        if(currentUserSubDetails.size() > 0)
            setCurrentUserSub(currentUserSubDetails);
        
        User[] us = [select Id, ProfileId, Title from User u where u.Id = :userId];
        if(us.size() > 0)
        {
            setCurrentUserTitle(us[0].Title);
            p = [select Id, Name from Profile p where p.Id = :us[0].ProfileId];
            if(p.size() > 0)
            {
                setUserProfileName(p[0].Name);
                
                users = ApexPages.currentPage().getParameters().get('ur');
                planGroupNames = ApexPages.currentPage().getParameters().get('pg');
                status = ApexPages.currentPage().getParameters().get('ss');
                templates = ApexPages.currentPage().getParameters().get('tp');
                if(templates != null)
                    templates = templates.replace('%20',' ');
                roles = ApexPages.currentPage().getParameters().get('rl');
    
            }
        }

    }

    public SearchPlanDocumentsVF()
    {
        currentUserSubDetails = [Select id, name, parentroleid, (select id, name, title from Users where IsActive = true and managerId != null order by name) from UserRole ur Where ur.ParentRoleId = :UserInfo.getUserRoleId() order by name];
        for(Integer i=0; i<currentUserSubDetails.size(); i++)
        {
            getRolesAtDeeperLevel(currentUserSubDetails[i]);
        }

        for(UserRole role: currentUserSubDetails)
        {
            for(User u : role.Users)
                uList.add(u);
        }
        
        if(currentUserSubDetails.size() > 0)
            setCurrentUserSub(currentUserSubDetails);
        
        User[] us = [select Id, ProfileId, Title from User u where u.Id = :UserInfo.getUserId()];
        if(us.size() > 0)
        {
            setCurrentUserTitle(us[0].Title);
            p = [select Id, Name from Profile p where p.Id = :us[0].ProfileId];
            if(p.size() > 0)
            {
                setUserProfileName(p[0].Name);
                
                users = ApexPages.currentPage().getParameters().get('ur');
                planGroupNames = ApexPages.currentPage().getParameters().get('pg');
                status = ApexPages.currentPage().getParameters().get('ss');
                templates = ApexPages.currentPage().getParameters().get('tp');
                if(templates != null)
                    templates = templates.replace('%20',' ');
                roles = ApexPages.currentPage().getParameters().get('rl');
                
            }
        }
    }
    

    private void getRolesAtDeeperLevel(UserRole ur)
    {
        UserRole[] roleList = [select id, name, ParentRoleId, (select id, name, title from Users where IsActive = true and managerId != null order by name)  from UserRole where ParentRoleId = :ur.id order by name];
        for(UserRole role: roleList)
            currentUserSubDetails.add(role);
    }
    
    
    /**
     * Used to display columns Template, Plan Group Name if User is an Admin
     * Hide the columns if User is an End User
    */
    public Boolean getDisplayColumns()
    {
        if(testVar == '')
        {
            Profile[] prof = [select Id, Name from Profile where Id = :UserInfo.getProfileId()];
            if(prof.size() > 0 && prof[0].Name == 'System Administrator')
            {
                dispColumns = true;
                return true;
            }
            else
            {
                 dispColumns = false;   
                 return false;
            }
        }
        return false;
    }
    
    public Sales_Contract__c getParticipant()
    {
        return tempSC;
    }
    
    public void setCurrentUserSub(UserRole[] cUser)
    {
        if(cUser != null && cUser.size() > 0)
            currentUserSubDetails = cUser;
    }
    
    public UserRole[] getCurrentUserSub()
    {
        if(currentUserSubDetails != null && currentUserSubDetails.size() > 0)
            return currentUserSubDetails;
        else
            return null;
    }
    
    public void setUserProfileName(String name)
    {
        userProfileName = name;
    }
    
    public String getUserProfileName()
    {
        return userProfileName;
    }
    
    public String getCurrentUserTitle()
    {
        return currentUserTitle;
    }
    
    public void setCurrentUserTitle(String name)
    {
        currentUserTitle = name;
    }
    
    
    public List<SelectOption> getUsersList() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('select','Select'));
        
        if(getUserProfileName() != 'System Administrator')
        {
            options.add(new SelectOption(UserInfo.getUserId(),UserInfo.getName()));
            userOptionList.add(UserInfo.getUserId());
            User cU = null;
            if(uList != null)
            {
                for(Integer i=0;i<uList.size(); i++)
                {
                    cU = uList[i];
                    options.add(new SelectOption(cU.Id,cU.Name));
                    userOptionList.add(cU.Id);
                }
            }
        }
        else
        {
            for(User[] user : [select Id, Name from User where IsActive = true order by FirstName])
            {
                if(user.size() > 0)
                {
                    for(User u : user)
                    {
                        options.add(new SelectOption(u.Id, u.Name));
                        userOptionList.add(u.Id);
                    }
                }
            }
        }
        return options;
    }
  
    public String getUsers() 
    {
        if(users == null)
            users = UserInfo.getUserId();
        return users;
    }
  
    public void setUsers(String users) {
        this.users = users;
    }
  
    public List<SelectOption> getRolesList() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('select','Select'));
        if(getUserProfileName() != 'System Administrator')
        {
            User[] u = [select UserRoleId, UserRole.Name from User where Id = :UserInfo.getUserId()];
            if(u.size() > 0)
            {
                options.add(new SelectOption(u[0].UserRoleId, u[0].UserRole.Name));
                rolesOptionList.add(u[0].UserRoleId);                
            }

            UserRole cU = null;
            if(currentUserSubDetails != null)
            {
                for(Integer i=0;i<currentUserSubDetails.size(); i++)
                {
                    cU = currentUserSubDetails[i];
                    options.add(new SelectOption(cU.Id,cU.Name));
                    rolesOptionList.add(cU.Id);
                }
            }
        }
        else
        {
            for(UserRole[] userRole : [select Id, Name from UserRole order by Name])
            {
                if(userRole.size() > 0)
                {
                    for(UserRole ur : userRole)
                    {
                        options.add(new SelectOption(ur.Id,ur.Name));
                        rolesOptionList.add(ur.Id);
                    }
                }
            }
        }
        return options;
    }
  
    public String getRoles() 
    {
        return roles;
    }
  
    public void setRoles(String roles) {
        this.roles = roles;
    }

    public List<SelectOption> getTemplatesList() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('select','Select'));
        for(Template__c[] templates : [select Name from Template__c order by Name])
        {
            if(templates.size() > 0)
            {
                for(Template__c t : templates)
                {
                    options.add(new SelectOption(t.Name, t.Name));
                }
            }
        }

/*        else
        {
            List<Template_Role__c> trList = new List<Template_Role__c>();
            Template_Role__c[] tr;
            if(currentUserTitle != null)
                tr = [select Template__c from Template_Role__c where User_Title__c = :currentUserTitle];

             if(tr.size() > 0)
             {
                 for(Template_Role__c tRole: tr)
                     trList.add(tRole);        
             }
             
             tr = [select Template__c from Template_Role__c where Role_ID__c = :UserInfo.getUserRoleId()];
             if(tr.size() > 0)
             {
                 for(Template_Role__c tRole: tr)
                     trList.add(tRole);        
             }
            if(currentUserSubDetails != null)
            { 
                for(Integer i=0; i<currentUserSubDetails.size(); i++)
                {
                    if(currentUserSubDetails[i].Id != null)
                        tr = [select Template__c from Template_Role__c where Role_ID__c = :currentUserSubDetails[i].Id];
                     
                     if(tr.size() > 0)
                     {
                         for(Template_Role__c tRole: tr)
                             trList.add(tRole);        
                     }
                }
            }
            if(uList != null && uList.size() > 0)
            {
                for(User u: uList)
                {
                     if(u.Title != null)
                         tr = [select Template__c from Template_Role__c where User_Title__c = :u.Title and Role_ID__c = null ];
                     
                     if(tr.size() > 0)
                     {
                         for(Template_Role__c tRole: tr)
                             trList.add(tRole);        
                     }
                }
            }    
            Template__c[] tList = new List<Template__c>();
            if(trList != null)
            {
                for(Integer i=0; i<trList.size(); i++)
                {
                    Template__c[] t = [select Id, Name from Template__c where Id = :trList.get(i).Template__c];
                    if(t.size() > 0)                
                        tList.add(t[0]);
                }    
                if(tList.size() > 0)
                {            
                    for(Template__c temp : tList)
                    {
                        options.add(new SelectOption(temp.Name, temp.Name));
                    }            
                }
            }
        }
        */
        return options;
    }
  
    public String getTemplates() 
    {
        return templates;
    }
  
    public void setTemplates(String templates) {
        this.templates = templates;
    }

    public List<SelectOption> getPlanGroupList() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('select','Select'));
        for(Batch__c[] batch : [select Id, Name,Status__c from Batch__c b where b.Status__c = 'Distributed' order by Name])
        {
            if(batch.size() > 0)
            {
                for(Batch__c b : batch)
                {
                    options.add(new SelectOption(b.Id,b.Name));
                }
            }
        }
        return options;
    }
  
    public String getPlanGroupNames() {
        return planGroupNames;
    }
  
    public void setPlanGroupNames(String planGroupNames) {
        this.planGroupNames = planGroupNames;
    }
    
    public List<SelectOption> getStatusList() 
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('select','Select'));
        //Display the below two status only if User is Admin.
        if(getDisplayColumns() == true)
        {
            options.add(new SelectOption('Draft','Draft'));
            options.add(new SelectOption('Distributed','Distributed'));
        }
        options.add(new SelectOption('Viewed','Viewed'));
        options.add(new SelectOption('Published','Published'));
        options.add(new SelectOption('Accepted','Accepted'));
        options.add(new SelectOption('Inquiry Submitted','Inquiry Submitted'));
        options.add(new SelectOption('Inquiry Approved','Inquiry Approved'));
        options.add(new SelectOption('Inquiry Rejected','Inquiry Rejected'));

        return options;
    }//end of getStatusList

    public String getStatus()
    {
        if(status == null)
        {
             status = 'Published';
        }

        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
  
    public Plan_Document_Inquiry__c getStartDate()
    {
//        pdi = [select Effective_Start_Date__c, Effective_End_Date__c from Plan_Document_Inquiry__c limit 1];
        return pdi;
    }    

    public List<Sales_Contract__c> getContracts()
    {
        return contracts;
    }
    
    public void setContracts(List<Sales_Contract__c> contracts) {
        this.contracts = contracts;
    }
    
    public PageReference doSearch()
    {
        ApexPages.currentPage().getParameters().put('ur', users);
        ApexPages.currentPage().getParameters().put('rl', roles);
        ApexPages.currentPage().getParameters().put('pg', planGroupNames);
        ApexPages.currentPage().getParameters().put('tp', templates);
        ApexPages.currentPage().getParameters().put('ss', status);
        String[] statusListEndUser = new String[]{'Viewed', 'Published', 'Accepted', 'Inquiry Submitted', 'Inquiry Approved', 'Inquiry Rejected'};

            if(contracts != null)
                contracts.clear();

/*            if(roles == null && planGroupNames == null && templates == null)
            {
                contracts = [select Id, Name, FirstName__c, LastName__c, TemplateName__c, BatchName__c, Plan_Document_Name__c, Status__c, UserRoleName__c, BatchID__c, UserID__c from Sales_Contract__c where Status__c = 'Published' and UserID__c = :UserInfo.getUserId() order by Name desc];
            }
  */              
/*            if(getUserProfileName() != '')
            {
                String formWhereClause = '';
                
                if(users != 'select')
                {
                    formWhereClause += ' where UserID__c = :users';
                    if(roles != 'select')
                        formWhereClause += ' and UserRoleId__c = :roles';
                    if(status != 'select')
                        formWhereClause += ' and Status__c = :status';
                    if(templates != 'select' && dispColumns == true)
                        formWhereClause += ' and TemplateName__c = :templates';
                    if(planGroupNames != 'select' && dispColumns == true)
                        formWhereClause += ' and BatchID__c = :planGroupNames';
;
                    formWhereClause += ' and Effective_Start_Date__c >= \''+salesContractObj[0].Effective_Start_Date__c+'\'';
                    if(status == 'select' && getUserProfileName() != 'System Administrator')
                    {
                        formWhereClause += ' and Status__c in :statusListEndUser';
                    }
                    
                    formWhereClause += ' order by Name desc';    
                }//end of if(users ! = 'select')

                else if(roles != 'select' && formWhereClause == '')
                {
                    formWhereClause += ' where UserRoleId__c = :roles';
                    if(status != 'select')
                        formWhereClause += ' and Status__c = :status';
                    if(templates != 'select' && dispColumns == true)
                        formWhereClause += ' and TemplateName__c = :templates';
                    if(planGroupNames != 'select' && dispColumns == true)
                        formWhereClause += ' and BatchID__c = :planGroupNames';

                    if(getUserProfileName() != 'System Administrator' && users == 'select')
                    {
                        Boolean flag = false;
                        if(UserInfo.getUserRoleId() == roles)
                        {
                            formWhereClause += ' and (UserID__c = \''+UserInfo.getUserId()+'\'';
                            flag = true;
                        }
                        
                        User u;
                        if(currentUserSubDetails != null)
                        {
                            for(Integer i=0;i<currentUserSubDetails.size(); i++)
                            {
                                u = currentUserSubDetails[i];
                                if(u.UserRoleId == roles)
                                {
                                    formWhereClause += ' or UserID__c =  \''+u.Id+'\'';  
                                    flag = true;
                                }
                            }
                        }
                        if(flag)
                            formWhereClause += ' )';
                    }    

                    if(status == 'select' && getUserProfileName() != 'System Administrator')
                    {
                        formWhereClause += ' and Status__c in :statusListEndUser';
                    }

                       
                    formWhereClause += ' order by Name desc';    
                }//end of if(users ! = 'select')
                
                else if(templates != 'select' && formWhereClause == '' && dispColumns == true)
                {
                    formWhereClause += ' where TemplateName__c = :templates';
                    if(roles != 'select')
                        formWhereClause += ' and UserRoleId__c = :roles';
                    if(status != 'select')
                        formWhereClause += ' and Status__c = :status';
                    if(planGroupNames != 'select')
                        formWhereClause += ' and BatchID__c = :planGroupNames';

                    if(getUserProfileName() != 'System Administrator' && users == 'select')
                    {
                        formWhereClause += ' and (UserID__c = \''+UserInfo.getUserId()+'\'';
                        User u;
                        for(Integer i=0;i<currentUserSubDetails.size(); i++)
                        {
                            u = currentUserSubDetails[i];
                            formWhereClause += ' or UserID__c =  \''+u.Id+'\'';  
                        }
                        formWhereClause += ' )';
                    }    
                        
                    formWhereClause += ' order by Name desc';    
                }//end of if(users ! = 'select')
                
                else if(status != 'select'  && formWhereClause == '')
                {
                    formWhereClause += ' where Status__c = :status';
                    if(users != 'select')
                        formWhereClause += ' and UserID__c = :users';
                    if(roles != 'select')
                        formWhereClause += ' and UserRoleId__c = :roles';
                     if(templates != 'select' && dispColumns == true)
                        formWhereClause += ' and TemplateName__c = :templates';
                    if(planGroupNames != 'select' && dispColumns == true)
                        formWhereClause += ' and BatchID__c = :planGroupNames';

                    if(getUserProfileName() != 'System Administrator' && users == 'select')
                    {
                        formWhereClause += ' and (UserID__c = \''+UserInfo.getUserId()+'\'';
                        User u;
                        for(Integer i=0;i<currentUserSubDetails.size(); i++)
                        {
                            u = currentUserSubDetails[i];
                            formWhereClause += ' or UserID__c =  \''+u.Id+'\'';  
                        }
                        formWhereClause += ' )';
                    }    
                    formWhereClause += ' order by Name desc';    
                }//end of if(users ! = 'select')

                else if(planGroupNames != 'select' && formWhereClause == '' && dispColumns == true)
                {
                    formWhereClause += ' where BatchID__c = :planGroupNames';

                    if(roles != 'select')
                        formWhereClause += ' and UserRoleId__c = :roles';
                     if(status != 'select')
                        formWhereClause += ' and Status__c = :status';
                    if(templates != 'select')
                        formWhereClause += ' and TemplateName__c = :templates';

                    if(getUserProfileName() != 'System Administrator' && users == 'select')
                    {
                        formWhereClause += ' and (UserID__c = \''+UserInfo.getUserId()+'\'';
                        User u;
                        for(Integer i=0;i<currentUserSubDetails.size(); i++)
                        {
                            u = currentUserSubDetails[i];
                            formWhereClause += ' or UserID__c =  \''+u.Id+'\'';  
                        }
                        formWhereClause += ' )';
                    }    
                        
                    formWhereClause += ' order by Name desc';    
                }//end of if(users ! = 'select')
                

                if(getUserProfileName() == 'System Administrator')
                {
                    if(formWhereClause != '')
                        contracts = Database.Query('select Id, Name,FirstName__c, LastName__c, TemplateName__c, BatchName__c, Plan_Document_Name__c, Status__c, UserRoleName__c, Effective_Start_Date__c, Effective_End_Date__c, BatchID__c, UserID__c from Sales_Contract__c '+formWhereClause);
                }
                else
                {
                    if(formWhereClause != '')
                        contracts = Database.query('select Id, Name, FirstName__c, LastName__c, Plan_Document_Name__c, Status__c, UserID__c, Effective_Start_Date__c, Effective_End_Date__c from Sales_Contract__c '+formWhereClause);
                 }
            }
    
*/
        String[] userList = new List<String>();
        String[] rolesList = new List<String>();

        if(users == 'select')
            userList = userOptionList;
        else
            userList.add(users);
            
        if(templates == 'select')
            templates = '%';
        if(planGroupNames == 'select')
            planGroupNames = '%';
        if(status == 'select')
            status = '%';
            
        if(roles == 'select')
            roles = '%';

  
        if(getUserProfileName() == 'System Administrator')
        {
	        contracts = [select Id, Name,FirstName__c, LastName__c, TemplateName__c, BatchName__c, Plan_Document_Name__c, Status__c, UserRoleName__c, Effective_Start_Date__c, Effective_End_Date__c, BatchID__c, UserID__c from Sales_Contract__c  where Effective_Start_Date__c >= :pdi.Effective_Start_Date__c and Effective_End_Date__c <= :pdi.Effective_End_Date__c and UserID__c in :userList and UserRoleId__c like :roles and Status__c like :status and BatchID__c like :planGroupNames and TemplateName__c like :templates order by CreatedDate desc];
	    }
        else
        {
            contracts = [select Id, Name,FirstName__c, LastName__c, Plan_Document_Name__c, Status__c, Effective_Start_Date__c, Effective_End_Date__c, UserID__c from Sales_Contract__c  where UserID__c in :userList and UserRoleId__c like :roles and Status__c like :status and Status__c in :statusListEndUser and Effective_Start_Date__c >= :pdi.Effective_Start_Date__c and Effective_End_Date__c <= :pdi.Effective_End_Date__c order by CreatedDate desc];
        }

        if(contracts.size() == 0)
            contracts = null;
        
        return null;
    }
   
    static testMethod void testGetTemplateAttachmentsVF() 
    {
        PageReference pg = Page.SearchPlanDocuments;
        
        Test.setCurrentPage(pg);

        SearchPlanDocumentsVF spvf = new SearchPlanDocumentsVF('005400000011epc', '00E40000000ju5m');
        spvf.getDisplayColumns();
        spvf.setCurrentUserSub(spvf.currentUserSubDetails);
        spvf.getCurrentUserSub();
        spvf.setUserProfileName('System Administrator');
        spvf.getUserProfileName();
        spvf.getUsersList();
        spvf.getRolesList();
        spvf.setCurrentUserTitle('Manager');
        spvf.getCurrentUserTitle();
        spvf.setRoles('00E80000000q1Ew');
        spvf.getRoles();
        spvf.getTemplatesList();

        spvf.setUserProfileName('Western Sales Team');
        spvf.getUserProfileName();
        spvf.getUsersList();
        spvf.getRolesList();
        spvf.setCurrentUserTitle('Manager');
        spvf.getCurrentUserTitle();
        spvf.setRoles('00E80000000q1Ew');
        spvf.getRoles();
        spvf.getTemplatesList();

        spvf.getPlanGroupList();
        
        spvf.setPlanGroupNames('a0B80000002BiXKEA0');
        spvf.getPlanGroupNames();
        
        spvf.dispColumns = true;
        spvf.getStatusList();
        
        spvf.status = null;
        spvf.getStatus();

        spvf.status = 'Published';
        spvf.getStatus();
        
        spvf.setStatus('Published');
        
        spvf.setContracts(spvf.contracts);
        spvf.getContracts();
        
        
        spvf.setCurrentUserTitle('CEO');
        spvf.getCurrentUserTitle();
        
        spvf.setUsers('00580000001UedX');        
        spvf.getUsers();
        
        spvf.setRoles('00E80000000q1Ew');
        spvf.getRoles();

        spvf.setTemplates('Spring 09');
        spvf.getTemplates();
        
        spvf.doSearch();
        spvf.users = 'select';
        spvf.setUserProfileName('Western Sales Team');
        spvf.doSearch();
    }
    
}//end of class